<template>
  <div class="notifications-container">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-wrapper">
      <el-skeleton :rows="10" animated />
    </div>

    <!-- 内容区域 -->
    <div v-else class="notifications-content">
      <h2 class="page-title">通知中心</h2>

      <el-tabs v-model="activeTab" class="notification-tabs">
        <!-- 系统通知标签页 -->
        <el-tab-pane label="系统通知" name="system">
          <el-table
              :data="systemNotifications"
              style="width: 100%"
              empty-text="暂无系统通知"
          >
            <el-table-column prop="title" label="标题" width="180"></el-table-column>
            <el-table-column prop="content" label="内容" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column prop="publishTime" label="发布时间" width="180">
              <template #default="{row}">
                {{ formatDate(row.publishTime) }}
              </template>
            </el-table-column>
            <el-table-column label="状态" width="100">
              <template #default="{row}">
                <el-tag :type="row.isRead ? 'success' : 'danger'" size="small">
                  {{ row.isRead ? '已读' : '未读' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180">
              <template #default="{row}">
                <el-button
                    size="small"
                    type="primary"
                    @click.stop="handleViewSystemNotification(row)"
                >
                  查看
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 活动通知标签页 -->
        <el-tab-pane label="活动通知" name="activity">
          <el-table
              :data="activityNotifications"
              style="width: 100%"
              empty-text="暂无活动通知"
              @row-click="handleActivityNotificationClick"
          >
            <el-table-column prop="activityTitle" label="活动名称"></el-table-column>
            <el-table-column prop="scheduleDate" label="排班日期" width="120">
              <template #default="{row}">
                {{ formatDate(row.scheduleDate) }}
              </template>
            </el-table-column>
            <el-table-column prop="location" label="活动地点"></el-table-column>
            <el-table-column prop="remark" label="备注"></el-table-column>
            <el-table-column label="状态" width="120">
              <template #default="{row}">
                <el-tag :type="getStatusTagType(row.status)" size="small">
                  {{ getStatusText(row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120">
              <template #default="{row}">
                <el-button
                    size="small"
                    :type="row.status === 0 ? 'primary' : 'info'"
                    @click.stop="handleConfirmActivity(row)"
                    :disabled="row.status !== 0"
                >
                  {{ row.status === 0 ? '确认' : '已确认' }}
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 系统通知详情对话框 -->
    <el-dialog
        v-model="systemDialogVisible"
        :title="currentSystemNotification.title"
        width="50%"
        @closed="handleSystemDialogClosed"
    >
      <div class="notification-detail">
        <p><strong>发布时间:</strong> {{ formatDateTime(currentSystemNotification.publishTime) }}</p>
        <div class="content-box">
          {{ currentSystemNotification.content }}
        </div>
      </div>
      <template #footer>
        <el-button type="primary" @click="systemDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 活动通知详情对话框 -->
    <el-dialog
        v-model="activityDialogVisible"
        :title="currentActivityNotification.activityTitle"
        width="50%"
    >
      <div class="notification-detail">
        <p><strong>活动时间:</strong> {{ formatDateTime(currentActivityNotification.scheduleDate) }}</p>
        <p><strong>活动地点:</strong> {{ currentActivityNotification.location }}</p>
        <p><strong>备注信息:</strong> {{ currentActivityNotification.remark || '无' }}</p>
        <p><strong>当前状态:</strong>
          <el-tag :type="getStatusTagType(currentActivityNotification.status)">
            {{ getStatusText(currentActivityNotification.status) }}
          </el-tag>
        </p>
      </div>
      <template #footer>
        <el-button
            type="primary"
            @click="handleConfirmActivity(currentActivityNotification)"
            :disabled="currentActivityNotification.status !== 0"
        >
          确认参加
        </el-button>
        <el-button @click="activityDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElLoading } from 'element-plus'
import axios from 'axios'
import { useRouter } from 'vue-router'

const router = useRouter()


// 响应式状态
const activeTab = ref('system')
const systemNotifications = ref([])
const activityNotifications = ref([])
const systemDialogVisible = ref(false)
const activityDialogVisible = ref(false)
const currentSystemNotification = ref({})
const currentActivityNotification = ref({})
const loading = ref(true)
const error = ref(null)

// 活动状态映射
const activityStatusMap = {
  0: '待确认',
  1: '已确认',
  2: '已拒绝',
  3: '已完成'
}

// 生命周期钩子
onMounted(() => {
  initialize()
})

// 初始化函数
const initialize = async () => {
  try {
    loading.value = true

    // 1. 获取用户ID
    // const userId = await fetchUserId()
    const userStr = localStorage.getItem('user');
    if (!userStr) {
      throw new Error('未获取到用户信息');
    }

    // ✅ 解析 JSON 并提取 username
    const userData = JSON.parse(userStr);
    const userId = userData.user.userId;
    if (!userId) {
      throw new Error('无法获取用户信息，请重新登录')
    }

    // 2. 获取通知数据
    const [systemNotices, activityNotices] = await Promise.all([
      fetchSystemNotifications(userId),
      fetchActivityNotifications(userId)
    ])

    systemNotifications.value = systemNotices
    activityNotifications.value = activityNotices

  } catch (err) {
    console.error('初始化失败:', err)
    error.value = err.message
    ElMessage.error(err.message)
  } finally {
    loading.value = false
  }
}

// 获取用户ID
const fetchUserId = async () => {
  // const username = localStorage.getItem('username')
  const userStr = localStorage.getItem('user');
  if (!userStr) {
    throw new Error('未获取到用户信息');
  }

  // ✅ 解析 JSON 并提取 username
  const userData = JSON.parse(userStr);
  const username = userData.user.username;
  if (!username) {
    throw new Error('用户未登录')
  }

  try {
    const response = await axios.get(BASE_URL+'/api/v1/users/getUserByUsername', {
      params: { username }
    })

    if (!response.data?.data?.userId) {
      throw new Error('无效的用户数据')
    }
    const user = response.data.data
    // return response.data.data.userId
    return user.value.userId
  } catch (err) {
    console.error('获取用户ID失败:', err)
    throw new Error('获取用户信息失败')
  }
}

// 获取系统通知数据
const fetchSystemNotifications = async (userId) => {
  try {
    const response = await axios.get(BASE_URL+'/api/v1/notices/system', {
      params: { userId }
    })
    return response.data?.data || []
  } catch (err) {
    console.error('获取系统通知失败:', err)
    throw new Error('获取系统通知失败')
  }
}

// 获取活动通知数据
const fetchActivityNotifications = async (userId) => {
  try {
    const response = await axios.get(BASE_URL+'/api/v1/notices/activity', {
      params: { userId }
    })
    return response.data?.data || []
  } catch (err) {
    console.error('获取活动通知失败:', err)
    throw new Error('获取活动通知失败')
  }
}

// 事件处理函数
const handleViewSystemNotification = (row) => {
  currentSystemNotification.value = row
  systemDialogVisible.value = true
}

const handleActivityNotificationClick = (row) => {
  currentActivityNotification.value = row
  activityDialogVisible.value = true
}

const handleSystemDialogClosed = async () => {
  if (!currentSystemNotification.value.isRead) {
    await markNoticeAsRead(currentSystemNotification.value.noticeId)
  }
}

const handleConfirmActivity = async (row) => {
  let loadingInstance = null
  try {
    loadingInstance = ElLoading.service({
      lock: true,
      text: '正在确认...'
    })

    await confirmActivitySchedule(row.scheduleId)

    // 更新本地状态
    const index = activityNotifications.value.findIndex(
        item => item.scheduleId === row.scheduleId
    )
    if (index !== -1) {
      activityNotifications.value[index].status = 1
    }

    ElMessage.success('活动确认成功')
    activityDialogVisible.value = false
  } catch (err) {
    console.error('确认活动失败:', err)
    ElMessage.error('确认活动失败')
  } finally {
    if (loadingInstance) {
      loadingInstance.close()
    }
  }
}

// API操作
const markNoticeAsRead = async (noticeId) => {
  try {
    const userId = await fetchUserId()

    await axios.post(BASE_URL+'/api/v1/notices/markRead', null, {
      params: {
        userId: userId,
        noticeId: noticeId
      }
    })

    // 更新本地状态
    const index = systemNotifications.value.findIndex(
        item => item.noticeId === noticeId
    )
    if (index !== -1) {
      systemNotifications.value[index].isRead = true
    }
  } catch (err) {
    console.error('标记已读失败:', err)
    ElMessage.error('标记已读失败')
    throw err
  }
}

const confirmActivitySchedule = async (scheduleId) => {
  try {
    const userId = await fetchUserId()
    await axios.post(BASE_URL+'/api/v1/activities/confirmSchedule', {
      scheduleId,
      userId
    })
  } catch (err) {
    console.error('确认活动失败:', err)
    throw err
  }
}

// 工具函数
const getStatusText = (status) => {
  return activityStatusMap[status] || '未知状态'
}

const getStatusTagType = (status) => {
  const map = {
    0: 'warning',
    1: 'success',
    2: 'danger',
    3: 'info'
  }
  return map[status] || ''
}

const formatDate = (dateString) => {
  if (!dateString) return ''
  return new Date(dateString).toLocaleDateString()
}

const formatDateTime = (dateString) => {
  if (!dateString) return ''
  return new Date(dateString).toLocaleString()
}
</script>

<style scoped>
.notifications-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.loading-wrapper {
  padding: 20px;
}

.page-title {
  margin-bottom: 20px;
  color: #303133;
}

.notification-tabs {
  margin-top: 20px;
}

.notification-detail {
  line-height: 1.8;
}

.content-box {
  margin-top: 15px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #f5f7fa;
}

.el-table {
  margin-top: 10px;
}

.el-table :deep(.el-table__row) {
  cursor: pointer;
}

.el-table :deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}
</style>